package com.noname.lib_base_java.net;

import com.google.gson.GsonBuilder;
import com.noname.lib_base_java.net.cache.HttpCache;
import com.noname.lib_base_java.net.cookies.CookieManger;
import com.noname.lib_base_java.net.interceptor.LoggingInterceptor;
import com.noname.lib_base_java.net.interceptor.NetInterceptor;
import com.noname.lib_base_java.util.AppUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: Lmoumou
 * Date: 2018-12-10 10:41
 * 文件名: RtManager
 * 描述:
 */
public class RtManager {
    private static final int TIMEOUT_READ = 60;
    private static final int TIMEOUT_CONNECTION = 60;

    private static RtManager instance;

    public static RtManager getInatance() {
        synchronized (RtManager.class) {
            if (instance == null) {
                instance = new RtManager();
            }
            return instance;
        }
    }

    private RtManager() {
    }

    private OkHttpClient okHttpClient = new OkHttpClient.Builder()
            //SSL
            .sslSocketFactory(TrustManager.getUnsafeOkHttpClient())
            .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
            //打印日志
            .addInterceptor(new LoggingInterceptor())
            //添加请求头
            .addInterceptor(new NetInterceptor())
            //设置Cache拦截器
            .cache(HttpCache.getCache())
            //设置Cookie
            .cookieJar(new CookieManger(AppUtils.getInstance().getContext()))
            //timeOut
            .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
            .writeTimeout(TIMEOUT_READ, TimeUnit.SECONDS)
            //失败重连
            .retryOnConnectionFailure(true)
            .build();


    public <T> T createApi(Class<T> clazz) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(NetManager.getInstance().getBaseUrl())
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()))
                .build();
        return retrofit.create(clazz);
    }
}
